package com.scqzy.shengchunqiang.sword2offer.day02;

import com.scqzy.shengchunqiang.structure.Node;

import java.util.Objects;

/**
 * @Description: 剑指 Offer 35. 复杂链表的复制
 * @Author 盛春强
 * @Date 2021/8/8 18:17
 */
public class CopyRandomList {
    public Node copyRandomList(Node head) {
        if (Objects.isNull(head)) {
            return null;
        }
        for (Node node = head, copy; Objects.nonNull(node); node = node.next.next) {
            copy = new Node(node.val);
            copy.next = node.next;
            node.next = copy;
        }
        for (Node node = head; Objects.nonNull(node); node = node.next.next) {
            if (Objects.nonNull(node.random)) {
                node.next.random = node.random.next;
            }
        }
        /**
         *
         */
        Node newHead = head.next;
        for (Node node = head, tmp; Objects.nonNull(node.next);) {
            tmp = node.next;
            node.next = tmp.next;
            node = tmp;
        }
        return newHead;
    }
}
